//
//  AppDelegate.m
//  iTotemMinFramework
//
//  Created by  on 12-8-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import <TencentOpenAPI/sdkdef.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "SinaWeibo.h"
#import "LoginViewController.h"
#import "Grammar.h"
#import "GrammarManager.h"
#import "Keyword.h"
#import "TagManager.h"
#import "Tag.h"
#import "Keyword.h"
#import "KeywordManager.h"
#import "CJSONDeserializer.h"

@implementation AppDelegate

static AppDelegate *appDelegate = nil;

+ (AppDelegate *)shareAppdelegate
{
    return appDelegate;
}

- (void)dealloc
{
    [_tencentOAuth release];
    [_sinaweibo release];
    [_window release];
    RELEASE_SAFELY(_homeTabbarController);
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    appDelegate = self;
    
    if (![USER_DEFAULT boolForKey:APP_HAS_LAUNCHED]) {
//        NSURL *url = [n]
        NSString *tagPath = [[NSBundle mainBundle] pathForResource: @"tag" ofType: @"json"];
        NSString *keywordPath = [[NSBundle mainBundle] pathForResource: @"keyword" ofType: @"json"];
         NSString *grammarPath = [[NSBundle mainBundle] pathForResource: @"grammar" ofType: @"json"];
        //定义一个NSError对象，用于捕获错误信息
        NSError *error;
        NSString *tagJsonString = [NSString stringWithContentsOfFile:tagPath encoding:NSUTF8StringEncoding error:&error];
        //将解析得到的内容存放字典中，编码格式为UTF8，防止取值的时候发生乱码
        NSDictionary *tagDic = [[CJSONDeserializer deserializer] deserialize:[tagJsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
        
        for (NSDictionary *atagDic in [tagDic objectForKey:@"tags"]) {
            Tag *aTag = [[Tag alloc] initWithDataDic:atagDic];
            [[TagManager sharedManager] addTag:aTag];
            [aTag release];
        }
        
        NSString *keywordJsonString = [NSString stringWithContentsOfFile:keywordPath encoding:NSUTF8StringEncoding error:&error];
        //将解析得到的内容存放字典中，编码格式为UTF8，防止取值的时候发生乱码
        NSDictionary *keywordDic = [[CJSONDeserializer deserializer] deserialize:[keywordJsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
        for (NSDictionary *akeywordDic in [keywordDic objectForKey:@"keywords"]) {
            Keyword *aKeyword = [[Keyword alloc] initWithDataDic:akeywordDic];
            [[KeywordManager sharedManager] addKeyword:aKeyword];
            [aKeyword release];
        }
        
        NSString *grammarJsonString = [NSString stringWithContentsOfFile:grammarPath encoding:NSUTF8StringEncoding error:&error];
        //将解析得到的内容存放字典中，编码格式为UTF8，防止取值的时候发生乱码
        NSDictionary *grammarDic = [[CJSONDeserializer deserializer] deserialize:[grammarJsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
        
        for (NSDictionary *agrammarDic  in [grammarDic objectForKey:@"grammars"]) {
            
            Grammar *aGrammar = [[Grammar alloc] initWithDataDic:agrammarDic];
            ITTDINFO(@" aGrammar %@",aGrammar);
            [GrammarManager sharedManager].grammarType = @"normal";
            [[GrammarManager sharedManager] addGrammar:aGrammar];
            [aGrammar release];
        }
        [USER_DEFAULT setBool:YES forKey:APP_HAS_LAUNCHED];
    }else {
        
    }
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    _homeTabbarController = [[HomeTabBarController alloc] init];
    self.window.rootViewController = _homeTabbarController;
    
    _sinaweibo = [[SinaWeibo alloc] initWithAppKey:kAppKey appSecret:kAppSecret appRedirectURI:kAppRedirectURI andDelegate:_loginViewController];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *sinaweiboInfo = [defaults objectForKey:@"SinaWeiboAuthData"];
    if ([sinaweiboInfo objectForKey:@"AccessTokenKey"] && [sinaweiboInfo objectForKey:@"ExpirationDateKey"] && [sinaweiboInfo objectForKey:@"UserIDKey"])
    {
        _sinaweibo.accessToken = [sinaweiboInfo objectForKey:@"AccessTokenKey"];
        _sinaweibo.expirationDate = [sinaweiboInfo objectForKey:@"ExpirationDateKey"];
        _sinaweibo.userID = [sinaweiboInfo objectForKey:@"UserIDKey"];
    }
    
    
    
    NSString *appid = @"100477973";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:_loginViewController];
    
    [_homeTabbarController release];
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    if (DATA_ENV.isQQConnect) {
        return [TencentOAuth HandleOpenURL:url];
    }else {
        return [_sinaweibo handleOpenURL:url];
    }
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if (DATA_ENV.isQQConnect) {
        return [TencentOAuth HandleOpenURL:url];
    }else {
        return [_sinaweibo handleOpenURL:url];
    }
    
}

- (void)syncDataRequest
{
    
}
@end
